<script setup>
import { ref, reactive, onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted,getCurrentInstance } from "vue"
import UploadImg from '@/components/UploadImg/index.vue';
import TopBar from '@/components/Topbar/index.vue'
import getRules from "@/validUtils";
import { addStore,getBrandType} from '@/api/BussinessMenage/index.js'
import {getAreaInfo,handleAddsChange,getAreaRolesInfo} from './Hooks'
import {getProvinceCityArea} from '@/utils/area.js'
import { useDistInfoStore } from '@/stores/dict.js'
import { useRoute,useRouter } from 'vue-router';
import AMapLoader from "@amap/amap-jsapi-loader"; // 按需引入依赖
import { closeTag } from '@/utils/globalWay'
const topBar = ref(null)
const route = useRoute();
const router = useRouter();
const distInfoStore = useDistInfoStore();
const tabName = ref('新增门店')
const backValue = ref('MerchantChildManageIndex')
const editLoading = ref(false)
const doorForm = ref({
  enterpriseId: route.query.id || '', // 商户id
  licenseName: '',//营业执照名称
  storeName: '', //门店名称
  affiliatMerchant: route.query.name || '', //所属商户
  license:'', //营业执照图片
  storeGroupId: route.query.storeGroupId ||  '', //门店分组
  fullAddr:'', //详细地址
  linkman:'',//联系人
  phone:'', //手机号码
  remark:'', //备注
  creditCode:'', //信用代码
  storeAddress:[], //地址码
  addressName:[], //地址名
  brandId:'',//品牌id
})
const brandGroupingDataList = ref([])

// 门店分组数据
const doorGroupingData = computed(()=>{
    return distInfoStore.getDistInfos("门店分组").map(lis=>{
        return {
            value:lis.id,
            label:lis.permissionName,
        }
    })
})




// 经营品牌数据
const brandGroupingData = computed(()=>{
    return distInfoStore.getDistInfos("经营品牌").map(lis=>{
        return {
            value:lis.id,
            label:lis.permissionName,
            type:lis.brandType
        }
    })
})

// 根据企业id获取品牌
const getBrandTypeList = async() => {
    try {
        let params = {
            enterpriseId:route.query.id || '',
            edit:false
        }
      const res = await getBrandType(params)
      console.log(res,'res');
      console.log(brandGroupingData.value,'doorGroupingData');
      if(res == 0){
        brandGroupingDataList.value = brandGroupingData.value.filter(item => item.type == 0)
      }else if(res == 1){
        brandGroupingDataList.value = brandGroupingData.value.filter(item => item.type == 1)
      }else if(res == -1){
        brandGroupingDataList.value = brandGroupingData.value
      }
      
    } catch (error) {
        
    }
}
getBrandTypeList()

// 营业执照名称校验规则
const validateDuplicateFun = (rule, value, callback) => {

        if(!value){
            callback(new Error("营业执照名称不可为空"));
        }
        // if(value == 111){
        //     callback(new Error("重名了"));
        // }
        else{
            callback()
        }
}
let validateDuplicateName = ref([{required:true, validator:validateDuplicateFun, trigger:"blur"}])

// 门店名称校验规则
const validateDoorDuplicateFun = (rule, value, callback) => {

if(!value){
    callback(new Error("门店名称不可为空"));
}
// if(value == 111){
//     callback(new Error("重名了"));
// }
else{
    callback()
}
}
let validateDoorName = ref([{required:true, validator:validateDoorDuplicateFun, trigger:"blur"}])

// 地址选择
const addressOptions = getAreaRolesInfo()

const handleAddsChanges = async(val,list) => {
 
    let obj = {
    address:[],
    regionId:[]
  }
    handleAddsChange(val,list,doorForm.value,obj,true)

}

// 图片上传
const backOcrValue = (ocrValue) => {
//   console.log(ocrValue,'ocrValue');
    doorForm.value.license = ocrValue.fileUrl || ''
    doorForm.value.creditCode = ocrValue.licenseNumber || ''
}

const otherParams = ref({
  type:'129001'
})

// 提交
const onSubmit = () => {
  console.log('submit!')
 
}
// 获取表单dom
const merchant = ref(null)
// 提交数据
const submit = () => {
    // console.log('ppppp');
    merchant.value.validate(async(valid) => { 
        console.log(valid,'valid');
        if(valid){
            try {
            editLoading.value = true
            console.log(doorForm.value.addressName,'5646546');
            let address = `${doorForm.value.addressName.join('')}${doorForm.value.fullAddr}`
            console.log(address,'address');
            let resultLoacation = JSON.parse(await getGecoder(address)) 
            console.log(resultLoacation,'resultLoacation');
            // if(!(resultLoacation && resultLoacation.length > 0)){
            //     ElMessage.error('详细地址与所选地区不一致，请进行调整')
            //     return
            // }
            // return
            let data = {
                ...doorForm.value,
                province:doorForm.value.addressName[0],
                city:doorForm.value.addressName[1],
                area:doorForm.value.addressName[2],
                provinceCode:doorForm.value.storeAddress[0],
                cityCode:doorForm.value.storeAddress[1],
                areaCode:doorForm.value.storeAddress[2],
                coordinate:{
                    lng:resultLoacation[0].location[0] || '',
                    lat:resultLoacation[0].location[1] || ''
                }
            }
            console.log(data,'data');
            const res = await addStore(data)
            closeTag(route.name)
            router.push({name:'MerchantChildManageIndex'})
            ElMessage.success('新增门店成功')
            } catch (error) {
                console.log(error);
            }finally{
                editLoading.value = false
            }
           
        }else{
           
            // TO DO ...
        }
    })
}


//高德地图地址解析
let lnglatCode = ref(null)
let map = null
let geocoder
let marker
const initMap = () => {
    window._AMapSecurityConfig = {
        securityJsCode: '',
    }
    AMapLoader.load({
        key:"123ea03b210596acf320c57e42c23f0d", // 申请好的Web端开发者Key，首次调用 load 时必填
        version:"2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins:['AMap.Geolocation', 'AMap.Geocoder'], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
    }).then((AMap)=>{
         geocoder = new AMap.Geocoder({ 
           city:''
        });
        map = new AMap.Map("container", {
        // 设置地图容器id
        // viewMode: "2D", // 是否为3D地图模式
        zoom: 11, // 初始化地图级别
        resizeEnable: true
        // center: [116.397428, 39.90923], // 初始化地图中心点位置
      });
      marker = new AMap.Marker()

    // console.log(map,'map');
        map.on('click',(e) => {
            // console.log(e,'e');
            regeoCode(e.lnglat)
        })
    }).catch(e=>{ 
        console.log(e);
    })

   

}
initMap()

// 地址解析定位
const geoCode = () => {
    let address = `${doorForm.value.addressName.join('')}${doorForm.value.fullAddr}`
        geocoder.getLocation(address, function(status, result) {
            if (status === 'complete'&&result.geocodes.length) {
                var lnglat = result.geocodes[0].location
                marker.setPosition(lnglat);
                map.add(marker);
                map.setFitView(marker);
            }else{
                console.log('根据地址查询位置失败');
            }
        });
}

// 地址逆解析定位
const regeoCode = (value) => {
        console.log(value,'value')
        let oooo = [value.lng,value.lat]
        return 
        var lnglat  = oooo
        console.log(lnglat,'lnglat');
        map.add(marker);
        marker.setPosition(lnglat);
        
        geocoder.getAddress(lnglat, function(status, result) {
            if (status === 'complete'&&result.regeocode) {
                console.log(result.regeocode,'result.regeocode');
                var address = result.regeocode.formattedAddress;
                console.log(address,'address');
                doorForm.value.fullAddr = address
                // document.getElementById('address').value = address;
            }else{
                console.log('根据经纬度查询地址失败')
            }
        });
    }

const getGecoder = (address) => {
    return new Promise((resolve,reject) => {
        geocoder.getLocation(address, (status, result) => {
            if (status === 'complete' && result.info === 'OK') {
                // result中对应详细地理坐标信息
                resolve(JSON.stringify(result.geocodes))
              
            }else{
                reject(new Error('获取地址失败!'))
            }
        })
    })

}

// 地图显示



const cancelBack = () => {
    topBar.value.backHandle()
    merchant.value.resetFields()
}

//组件挂载到节点上之前执行的函数
onBeforeMount(()=>{})

//组件挂载完成后执行的函数
onMounted(()=>{
})

//组件更新之前执行的函数
onBeforeUpdate(()=>{})

//组件更新完成之后执行的函数
onUpdated(()=>{})

//组件卸载之前执行的函数
onBeforeUnmount(()=>{})

//组件卸载完成后执行的函数
onUnmounted(()=>{})

</script>

<template>
  <div class="edit-page" v-loading="editLoading">
    <TopBar ref="topBar" :backValue="backValue" :tabName="tabName">
        <template #operate>
            <div>
                <el-button @click="cancelBack">取消</el-button>
                <el-button type="primary" @click="submit">确定</el-button>
            </div>
        </template>
    </TopBar>
    <div class="main">
        <el-form :inline="true" :model="doorForm" class="demo-form-inline" ref="merchant" label-width="110px">
        <div class="basic">
            <div class="title-view">
                <div class="icon-view">
                    <div class="icon-view-on"></div>
                </div>
                <div class="title">基础信息</div>
            </div>
            <div class="basic-form">
                    <el-form-item label="营业执照名称" :rules="validateDuplicateName" prop="licenseName">
                        <el-input 
                        v-model="doorForm.licenseName"
                        placeholder="请输入" 
                        maxlength="50"
                        show-word-limit
                        clearable/>
                    </el-form-item>
                    <el-form-item label="门店名称" :rules="validateDoorName" prop="storeName">
                      <el-input 
                      v-model="doorForm.storeName" 
                      placeholder="请输入" 
                      maxlength="50"
                      show-word-limit
                      clearable
                       />
                    </el-form-item>
                    <el-form-item label="所属商户">
                        <el-input 
                            v-model="doorForm.affiliatMerchant" 
                            placeholder="请输入" 
                            maxlength="50"
                            show-word-limit
                            clearable
                            disabled
                            />
                    </el-form-item>
                    <el-form-item style="margin-bottom: 10px;" label="所属地区" :rules="getRules('select','所属地区')" prop="storeAddress">
                        <el-cascader
                        v-model="doorForm.storeAddress"
                        :options="addressOptions"
                        :props="{value:'area_code',label:'area_name',children:'children'}"
                        @change="(e)=>handleAddsChanges(e,addressOptions)"
                        style="width:100%"
                        >
                    </el-cascader>
                    </el-form-item>
                   
                    <el-form-item label="" style="margin-left: -35px; margin-bottom: 10px;" :rules="getRules('input','详细地址')" prop="fullAddr">
                      <el-input v-model="doorForm.fullAddr" placeholder="请输入" clearable />
                     <div class="point-icon"  @click="geoCode">
                        <img style="width: 12px; height: 14px;" src="https://static.91medicine.net/images/20231219/726619a7-fce2-4177-a08e-add8ab7b1366.png" alt="">
                     </div>
                    </el-form-item>
                   
                     <el-form-item label="门店分组" style="margin-left: 146px;">
                        <el-select
                            v-model="doorForm.storeGroupId"
                            placeholder="请选择"
                            disabled
                        >
                        <el-option
                          v-for="it in doorGroupingData"
                          :key="it.value"
                          :label="it.label"
                          :value="it.value"
                      />
                        </el-select>
                    </el-form-item>

                    <div class="map-view">
                        <div class="tips">
                            若门店实际地址与营业执照的地址有差异，可以在地址末尾增加括号备注，便于审核判断。比如营业资质地址(实际地址)
                        </div>
                        <div id="container"></div>
                    </div>
                    
                    <el-form-item label="联系人" :rules="getRules('input','联系人')" prop="linkman">
                       <el-input 
                       v-model="doorForm.linkman" 
                       placeholder="请输入" 
                       clearable 
                       maxlength="20"
                       show-word-limit
                       />
                    </el-form-item>
                    <el-form-item label="手机号码" :rules="getRules('phone', '手机号')" prop="phone">
                       <el-input v-model="doorForm.phone" placeholder=" 请输入" clearable />
                    </el-form-item>
            </div>
        </div>
        <div class="business">
            <div class="title-view">
                <div class="icon-view">
                    <div class="icon-view-on"></div>
                </div>
                <div class="title">经营信息</div>
            </div>


                <div class="bussiness-form">
                    <el-form-item label="营业执照"  style="margin-bottom: 32px;">
                        <UploadImg 
                            :action="'/gateway/jy-business/ocr/upload/ocrSingle'"
                            @backValue="backValuelicense" 
                            @backOcrValue="backOcrValue"
                            :imageUrlInfo="doorForm.license"
                            :maxImgLength="1"
                            :otherParams="otherParams"
                        >
                            <template #tips>
                                <div style="font-size:12px;color:#666;line-height:18px;margin-top:5px;position:absolute;width:260px">支持jpg、jpeg、png格式不超过5M</div>
                            </template>
                        </UploadImg>
                    </el-form-item>
                    <el-form-item style="margin-left: 192px;" label="经营品牌"  :rules="getRules('select','经营品牌')" prop="brandId">
                    <el-select
                        v-model="doorForm.brandId"
                        placeholder="请选择"
                        clearable
                    >
                    <el-option
                          v-for="it in brandGroupingDataList"
                          :key="it.value"
                          :label="it.label"
                          :value="it.value"
                      />
                    </el-select>
                    </el-form-item>
                    <el-form-item label="备注">
                        <el-input v-model="doorForm.remark" placeholder="请输入" clearable maxlength="100" show-word-limit/>
                    </el-form-item>
                    <el-form-item label="组织信用代码">
                        <el-input v-model="doorForm.creditCode" placeholder="请输入" disabled />
                    </el-form-item>
                </div>
        </div>
    </el-form>
    </div>
  </div>
</template>

<style lang="less" scoped>
    .edit-page{
        width: 100%;
        height: 100%;
        .main{
            width: 1600px;
            height: calc(100% - 48px);
            overflow: auto;
            box-sizing: border-box;
            padding: 24px;
             // 基础信息样式
         .basic{
            margin-bottom: 8px;

            .basic-form{
                margin-left: 20px;
            }
         
         }
        //  账户信息样式
         .account-info{
            margin-bottom: 8px;
            .account-form{
                margin-left: 20px;
            }
        // 经营信息样式
         }
         .business{
            margin-bottom: 8px;
            .bussiness-form{
                margin-left: 20px;
            }
         }
        }
       
    }
    .title-view{
                display: flex;
                align-items: center;
                margin-bottom: 16px;
                .icon-view{
                    margin-right: 8px;
                    position: relative;
                    width: 14px;
                    height: 14px;
                // background-color: red ;
                // background-repeat: no-repeat;
                // background-size: 7px 7px;
                    &::before {
                        content: "";
                        position: absolute;
                        top: 0;
                        left: 0;
                        width: 10px;
                        height: 10px;
                        border-radius: 2px;
                        background-color: #10E7F9; 
                    }
                    .icon-view-on{
                        position: absolute;
                        bottom: 0;
                        right: 0;
                        width: 10px;
                        height: 10px;
                        border-radius: 2px;
                        background-color: #3480FF; /* 背景色 */
                    }
            }
            .title{
                color: #000000;
                font-family: "PingFang SC";
                font-size: 14px;
                font-style: normal;
                font-weight: 600;
                line-height: 14px;
            }
            }

    .el-form-item{
        margin: 0 39px 16px 0;
        :deep(.el-input) {
          width: 350px;
        }
    }

    .map-view{
        width: 700px;
        padding-left: 110px;
        margin-bottom: 16px;
        .tips{
            margin-bottom: 10px;
            color: #666666;
            font-family: "PingFang SC";
            font-size: 12px;
            font-style: normal;
            font-weight: 400;
            line-height: 18px;
        }
        #container{
            width: 530px;
            height: 200px;
        // background: #10E7F9;
    }
    }
    .point-icon{
        position: absolute;
        top: 2px;
        right: 33px;
        cursor: pointer;
    }
   
</style>
